﻿@using Telerik.Web.Mvc.UI;
@using Nop.Web.Framework.Web;
@using Nop.Services.Security;
@using Nop.Core.Domain.Security;
@{
    if (!Telerik.Web.Mvc.SiteMapManager.SiteMaps.ContainsKey("admin"))
    {
        Telerik.Web.Mvc.SiteMapManager.SiteMaps.Register<Telerik.Web.Mvc.XmlSiteMap>("admin", sitemap =>
            sitemap.LoadFrom("~/Administration/sitemap.config"));
    }
    var adminMenuPlugins = EngineContext.Current.Resolve<Nop.Core.Plugins.IPluginFinder>().GetPlugins<IAdminMenuPlugin>();

    var permissionService = EngineContext.Current.Resolve<IPermissionService>();
    var hideAdminMenuItemsBasedOnPermissions = EngineContext.Current.Resolve<SecuritySettings>().HideAdminMenuItemsBasedOnPermissions;
}
@{
    Html.Telerik().Menu().Name("Admin")
    .BindTo("admin", (item, siteMapNode) =>
    {
        var imageUrl = ((Telerik.Web.Mvc.SiteMapNode)siteMapNode).Attributes["ImageUrl"];
        if (imageUrl != null && !string.IsNullOrEmpty(imageUrl.ToString()))
        {
            item.ImageUrl = imageUrl.ToString();
        }
        
        var resourceName = ((Telerik.Web.Mvc.SiteMapNode)siteMapNode).Attributes["nopResource"];
        if (resourceName != null && !string.IsNullOrEmpty(resourceName.ToString()))
        {
            item.Text = T(resourceName.ToString()).ToHtmlString();
        }

        if (ViewBag.SelectedMenuItem == item.Text)
        {
            item.Selected = true;
        }

        if (hideAdminMenuItemsBasedOnPermissions)
        {
            var permissionNames = ((Telerik.Web.Mvc.SiteMapNode)siteMapNode).Attributes["PermissionNames"];
            if (permissionNames != null && !string.IsNullOrEmpty(permissionNames.ToString()))
            {
                item.Visible = permissionNames.ToString().Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)
                    .Any(permissionName => permissionService.Authorize(permissionName.Trim()));
            }
        }        
    })
    .Items(x =>
    {
        if (adminMenuPlugins.Count() > 0)
        {
            if (!hideAdminMenuItemsBasedOnPermissions || 
                permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                x.Add().Text(T("Admin.Plugins").ToHtmlString()).Items(y =>
                {
                    foreach (var adminMenuPlugin in adminMenuPlugins)
                    {
                        adminMenuPlugin.BuildMenuItem(y.Add());
                    }
                });
            }
        }
    })
    .OpenOnClick(false)

    .Render();
}
